package cn.com.bluemoon.daps.model.core.file.export.impl;

import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.exception.DapThrowException;
import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.model.core.file.export.BaseFileExport;
import cn.com.bluemoon.daps.model.core.file.export.FileExport;
import cn.com.bluemoon.daps.model.core.file.parser.FileType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author Jarod.Kong
 * @date 2021/3/23 9:40
 */
@Slf4j
public class WorkbookFileExport extends BaseFileExport<String> {
    /**
     * 导出动作
     *
     * @param fileExport 导出对象
     * @return 结果
     */
    @Override
    public ResultBean<String> export(FileExport fileExport) {
        check0(fileExport);
        BmAssetUtils.isTrue(FileType.EXCEL.equals(fileExport.getFileType()), "针对excel文件进行输出流下载");
        HttpServletResponse servletResponse = fileExport.getHttpServletResponse();
        BmAssetUtils.notNull(servletResponse, "文件以输出流方式进行下载，必须传递HttpServletResponse");
        File file = fileExport.getFile();
        webDownloadFileByResponse(file, servletResponse);
        return ResultBean.ok("导出完成");
    }

    /**
     * web输出Excel文件
     *
     * @param file     Excel
     * @param response x
     */
    private void webDownloadFileByResponse(File file, HttpServletResponse response) {
        try {
            Workbook workbook = WorkbookFactory.create(file);
            commonDownload(response, workbook, file.getName());
        } catch (IOException e) {
            log.error("文件不是excel格式", e);
            throw new DapThrowException("文件不是excel格式！");
        } catch (Exception e) {
            log.error("系统导出功能异常", e);
            throw new DapThrowException("系统导出功能异常");
        }
    }

    /**
     * 针对下载excel文件的方式（流）
     *
     * @param response
     * @param workbook
     * @param fileName
     */
    public static void commonDownload(HttpServletResponse response, Workbook workbook, String fileName) {
        try {
            BmAssetUtils.notNull(workbook, "文档对象不为空！！");
            String fileEncode = StandardCharsets.UTF_8.name();
            // 告诉浏览器输出内容为流
            response.setHeader("Content-Type", "application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''"
                    + URLEncoder.encode(fileName, fileEncode));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException ex) {
            log.error("下载文件异常", ex);
            throw new DapThrowException("下载文件异常," + ex.getMessage());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error("下载文件异常", e);
            }
        }
    }


}
